<template>
  <div class="sftp">
    <!-- Main Wrapper -->
    <div class="main-wrapper">
      <Header/>
      <SideBar/>
      <!-- Page Wrapper -->
      <div class="page-wrapper"><!-- :is="currentView" -->
        <div class="content container-fluid">
          <BreadCrumb/>
          <h2>我的sftp账户</h2>
          <el-button type="primary" size="mini" @click="() => add()">新增账户</el-button><br>
            <el-table
		      border
		      style="width: 100%"
		      align="center"
		      @selection-change="handleSelectionChange"
		      :data="tableData">
		              <el-table-column prop="sftpUsername" label="账号"> </el-table-column>
		              <el-table-column prop="sftpPassword" label="密码"> </el-table-column>
                      <el-table-column prop="owner_name" label="所属用户"> </el-table-column>
		              <el-table-column prop="owner_tno" label="用户工号"> </el-table-column>
                      <el-table-column prop="activateStatus" label="账号状态"> </el-table-column>
                      <el-table-column label="操作" style="width: 20%">
                        <template slot-scope="scope">
                            <el-button @click="() => user_del(scope.$index, tableData)" type="text" size="small">删除</el-button>
                        </template>
                      </el-table-column>
		    </el-table>
		    <el-col :span="24" class="xtes">
		      <el-col :span="24" >
		        <div class="xtesbox">
		        <el-pagination
		                  @size-change="handleSizeChange"
		                  @current-change="handleCurrentChange"
		                  :current-page="currentPage"
		                  :page-sizes="[10, 20, 30, 40]"
		                  :page-size="pageSize"
						  class
		                  layout="total, sizes, prev, pager, next, jumper"
		                  :total="total"
		                >
		                </el-pagination></div>
		      </el-col>
		    </el-col>
          <br>
          <br>
          <hr>
          <h2>文件管理</h2>
        <el-main class="system">

        账号：<el-input v-model="username" placeholder="SFTP用户名" class="account"></el-input>
        密码：<el-input v-model="password" placeholder="密码" class="account" show-password clearable></el-input>
        主机：<el-input v-model="host" placeholder="主机IP" class="account"></el-input>
        端口：<el-input v-model="port" placeholder="端口号" class="account2"></el-input>
        &nbsp;
        <el-button type="primary" @click="init_loadNode">初始化</el-button>
      </el-main>
        <el-tree
        :props="props"
        :load="loadNode"
        lazy> <!--show-checkbox-->
        <!-- 自定义tree内容 -->
        <span class="custom-tree-node" slot-scope="{ node, data }">
            <span >{{ node.label }}<font style="color: blue">({{data.type}})</font></span>
            <template v-if="data.type==='File'&&data.type!='Dir'">
            <span>
            <el-button type="text" size="mini" @click="() => sftpDownload(node, data)">Download</el-button>
            </span>
            </template>
        </span>
        </el-tree>

<el-dialog
  title="新增SFTP用户"
  :visible.sync="addDialogVisible"
  width="30%">
  <span>账号：</span><el-input placeholder="请设置账号" v-model="add_username"></el-input><br>
  <span>密码：</span><el-input placeholder="请设置密码" v-model="add_password" show-password clearable></el-input><br>
  <span slot="footer" class="dialog-footer">
    <el-button @click="addDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="user_add()">确 定</el-button>
  </span>
</el-dialog>

        </div>
      </div>
      <!-- /Page Wrapper -->
    </div>
  </div>
</template>

<script>
// @ is an alias to /src
import BreadCrumb from '@/components/Breadcrumb'
import Header from '@/components/Header'
import SideBar from '@/components/SideBar'
// tree展示代码范例传送门（https://element.eleme.cn/#/zh-CN/component/tree#fang-fa）
export default {
  created(){
      this.queryAccount()
  },
  beforeDestroy(){
  },
  mounted(){
  },
  data(){
      return {
        // 个人账号
        currentPage: 1,
		pageSize: 10,
		total: 0,
        multipleSelection: [],
        tableData: [],
        // tree
        props: {
          label: 'name',
          children: 'zones'
        },
        // 参数
        // username: '',
        // password: '',
        // host: '',
        username: 'abcabc',
        password: 'abcsftp',
        host: '121.196.16.146',
        port: '22',
        // 初始化
        init_node: {},
        init_resolve: {},
        // add user
        addDialogVisible: false,
        add_username: '',
        add_password: '',
      }
  },
  methods: {
      // query personnel account
      queryAccount(){
        let config = {
            method: 'post',
            url: 'edu/sftp/list_staff_sftp',
            headers: {
                "Content-Type": "application/json;"
            },
            data: {
                userId: localStorage.getItem('userId'),
                pageNum: this.currentPage,
                pageSize: this.pageSize
            }
        };
        this.$http(config)
        .then((response)=>{
            if (response.data.statusCode == 1){
                this.tableData = response.data.page.list
                this.total = response.data.page.totalCount
            }else{
                this.$message.warning(response.data.msg);
            }
        }).catch(error => {
            this.$message.error("query failed, please try again later.");
            console.log(error)
        });
      },
      init_loadNode(){
        let config = {
            method: 'post',
            url: 'edu/sftp/sftp_nodes',
            headers: {
                "Content-Type": "application/json;"
            },
            data: {
                username: this.username,
                password: this.password,
                host: this.host,
                port: this.port,
                path: '/' //+ this.username
            }
        };
        this.$http(config)
        .then((response)=>{
            if (response.data.statusCode == 1){
                this.init_resolve(response.data.list)
            }else{
                this.$message.warning(response.data.msg);
            }
        }).catch(error => {
            this.$message.error("query failed, please try again later.");
            console.log(error)
        });
      },
      // 
      loadNode(node, resolve) {
        // 自定义初始化时赋值用，仅一次(加载当前页面的生命周期开始时)
        if (node.level === 0) {
            this.init_node = node
            this.init_resolve = resolve
        }
        // 初始化之后的
        if ( node.level > 0 ){
            // 非子节点，即非目录
            if (node.data.isLeaf === false) {
                return resolve([])
            }
            // 属于目录的，允许向下延伸
            let config = {
                method: 'post',
                url: 'edu/sftp/sftp_nodes',
                headers: {
                    "Content-Type": "application/json;"
                },
                data: {
                    username: this.username,
                    password: this.password,
                    host: this.host,
                    port: this.port,
                    path: node.data.path + '/' + node.data.name
                }
            };
            this.$http(config)
            .then((response)=>{
                if (response.data.statusCode == 1){
                    return resolve(response.data.list)
                }else{
                    this.$message.warning(response.data.msg);
                }
            }).catch(error => {
                this.$message.error("query failed, please try again later.");
                console.log(error)
            });
            return resolve([])
        }
      },
      sftpDownload(node, data){
        console.log(node)
        console.log(data)
        let config = {
            method: 'post',
            url: 'edu/sftp/download_file',
            responseType: 'blob',
            headers: {
                "Content-Type": "application/json;"
            },
            data: {
                username: this.username,
                password: this.password,
                host: this.host,
                port: this.port,
                path: node.data.path,
                down_filename: node.data.name
            },
            timeout: 1000 * 60    // 单位：毫秒，响应若超过1分钟即不再等待请求。这并不是指60秒内未下载完文件就会中断下载
        };
        this.$http(config)
        .then((response) => {
            // 提取文件名
            const filename = decodeURI(response.headers["content-disposition"].split("fileName=")[1])
            console.log(filename)
            // 将二进制流转为blob
            const blob = new Blob([response.data], {
                type: 'application/octet-stream'
            })
            if (typeof window.navigator.msSaveBlob !== 'undefined') {
                // 兼容IE，window.navigator.msSaveBlob：以本地方式保存文件
                window.navigator.msSaveBlob(blob, filename)
            } else {
                // 创建新的URL并指向File对象或者Blob对象的地址
                const blobURL = window.URL.createObjectURL(blob)
                // 创建a标签，用于跳转至下载链接
                const tempLink = document.createElement('a')
                tempLink.style.display = 'none'
                tempLink.href = blobURL
                tempLink.setAttribute('download', filename)
                // 兼容：某些浏览器不支持HTML5的download属性
                if (typeof tempLink.download === 'undefined') {
                    tempLink.setAttribute('target', '_blank')
                }
                // 挂载a标签
                document.body.appendChild(tempLink)
                tempLink.click()
                document.body.removeChild(tempLink)
                // 释放blob URL地址
                window.URL.revokeObjectURL(blobURL)
            }
        }).catch(error => {
            this.$message.error("下载失败，请重试或者联系管理员");
            console.log(error)
        });
      },
      handleSizeChange(val) {
        this.pageSize = val;
        this.queryAccount()
        // console.log(`每页 ${val} 条`);
        },
        handleCurrentChange(val) {
        this.currentPage = val;
        this.queryAccount()
        // console.log(`当前页: ${val}`);
        },
    handleSelectionChange(data) {
        // console.log('获取row', data)
        // 当前多选的数据
        this.multipleSelection = data;
    },
        add(){
            this.add_username = ''
            this.add_password = ''
            this.addDialogVisible = true
        },
    user_add(){
        let config = {
            method: 'post',
            url: 'edu/sftp/sftp_user_mag',
            headers: {
                "Content-Type": "application/json;"
            },
            data: {
                oprate_type: 'add',
                username: this.add_username,
                password: this.add_password,
                user_id: localStorage.getItem('userId'),
            }
        };
        this.$http(config)
        .then((response)=>{
            if (response.data.statusCode == 1){
                this.addDialogVisible = false
                this.queryAccount()
            }else{
                this.$message.warning(response.data.msg);
            }
        }).catch(error => {
            this.$message.error("query failed, please try again later.");
            console.log(error)
        });
    },
    user_del(index, rows){
        let config = {
            method: 'post',
            url: 'edu/sftp/sftp_user_mag',
            headers: {
                "Content-Type": "application/json;"
            },
            data: {
                oprate_type: 'del',
                username: rows[index].sftpUsername,
                user_id: localStorage.getItem('userId'),
            }
        };
        this.$http(config)
        .then((response)=>{
            if (response.data.statusCode == 1){
                // this.queryAccount()
                rows.splice(index, 1);
                this.$message.success(response.data.msg);
            }else{
                this.$message.warning(response.data.msg);
            }
        }).catch(error => {
            this.$message.error("query failed, please try again later.");
            console.log(error)
        });
    }

  },
  components: {
	Header,
    BreadCrumb,
	  SideBar
  }
}
</script>

<style>
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
  .system {
    background-color: #fff;
    border-radius: 0 0 15px 15px;
    font-size: 18px;
  }
  .account{
    width: 200px;
    height: 35px;
    margin-bottom: 20px;
    padding-left: 10px;
  }
  .account2{
    width: 88px;
    height: 35px;
    margin-bottom: 20px;
    padding-left: 10px;
  }
</style>